<?php
header('P3P: CP="CAO PSA OUR"');
require_once ("../utils/query.php");

session_start();
if(empty($_SESSION['facebook_id']))
	die("Not logged into facebook.");
$facebook_id = $_SESSION['facebook_id'];

$result = execute_query("SELECT drupaluid FROM facebookUser WHERE facebookID = '%s'", $facebook_id);
$registered = false;
if($result) {
	$row = mysql_fetch_assoc($result);
	if($row) {
		$_SESSION['untold_id'] = $row['drupaluid'];
		$registered = true;
	}
}
?>
<html>
	<head>
		<script type="text/javascript" src=<?php echo LIB_JQUERY; ?>></script>
		<script type="text/javascript">
			var keyDownEnter = false;
			
			function onSubmit()	{
				$.post(
					"../ajax/registerFacebookUser.php",
					{
						drupal_id: $("#drupalid").val(),
						drupal_pw: $("#drupalpw").val()
					},
					function(data) {
						if (data.success) {
							$("#message").html("Registration successful.");
							$("#table").hide();
						} else {
							alert(data.message);
							if(event.keyCode != 13)
								keyDownEnter = false;
						}
					},
					'json'
				);
			}
			
			function onKeyDown() {
				if(event.keyCode == 13 && !keyDownEnter) { // enter is key code 13.
					keyDownEnter = true;
					onSubmit();
				}
			}
			
			function onKeyUp() {
				if(event.keyCode == 13 && keyDownEnter)
					keyDownEnter = false;
			}
			
			document.onkeyup = onKeyUp;
		</script>
	</head>
	<body>
		<a href="testList.php">Back to list</a><br><br>
		<?php
		if($registered) {
			echo "Already registered.";
		} else {
		?>
		<div id="message">Enter your Untold credentials.</div>
		<table id="table">
			<tr>
				<td>Username: </td>
				<td><input id="drupalid" type="text" name="drupalid" onkeydown="onKeyDown(event.which)"></input></td>
			</tr>
			<tr>
				<td>Password: </td>
				<td><input id="drupalpw" type="password" name="drupalpw" onkeydown="onKeyDown(event.which)"></input></td>
			</tr>
			<tr>
				<td><a href="http://testsite.untoldthegame.com/user/register" target="_blank">Register</a></td>
				<td><input id="login" type="submit" value="Log In" onclick="onSubmit()" /></td>
			</tr>
		</table>
		<?php
		}
		?>
	</body>
</html>
